package com.atguigui.leetcode;

import java.util.Arrays;

/**
 * 676.实现一个魔法字典
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/7/11 10:20
 */
public class P676ImplementMagicDictionary {
    public static void main(String[] args) {
        MagicDictionary solution = new P676ImplementMagicDictionary().new MagicDictionary();

        String[] str = {"hello", "hallo", "leetcode", "judge"};
        solution.buildDict(str);
        boolean juage = solution.search("juage");
        System.out.println(juage);

        // TO TEST
    }

    /**
     * 放到一个数组中，比较字符串长度相等，且只有一个不同的单词
     * 执行用时：27 ms, 在所有 Java 提交中击败了67.99%的用户
     * 内存消耗：42.1 MB, 在所有 Java 提交中击败了67.99%的用户
     */
    class MagicDictionary {
        String[] dict;

        public MagicDictionary() {
        }

        public void buildDict(String[] dictionary) {
            dict = dictionary.clone();
            Arrays.sort(dict);
        }

        public boolean search(String searchWord) {
            for (String str : dict) {
                if (str.length() == searchWord.length()) {
                    int num = 0;
                    char[] wordChar = searchWord.toCharArray();
                    char[] strChar = str.toCharArray();
                    for (int i = 0; i < wordChar.length; i++) {
                        if (num > 1) {
                            break;
                        }
                        if (strChar[i] != wordChar[i]) {
                            num++;
                        }
                    }
                    if (num == 1) {
                        return true;
                    }
                }
            }

            return false;
        }
    }
}
